<!DOCTYPE HTML>
<html lang>
<head><meta name="generator" content="Hexo 3.9.0">
    <!--Setting-->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="IE=Edge,chrome=1">
    <meta http-equiv="Cache-Control" content="no-siteapp">
    <meta http-equiv="Cache-Control" content="no-transform">
    <meta name="renderer" content="webkit|ie-comp|ie-stand">
    <meta name="apple-mobile-web-app-capable" content="腾宇的个人博客">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <meta name="format-detection" content="telephone=no,email=no,adress=no">
    <meta name="browsermode" content="application">
    <meta name="screen-orientation" content="portrait">
    <meta name="theme-version" content="1.2.3">
    <meta name="root" content="/blog/">
    <link rel="dns-prefetch" href="https://gitee.com/bingtengaoyu/blog">
    <!--SEO-->

    <meta name="keywords" content>


    <meta name="description" content="JQ 中怎么样编写插件？@(作者)[腾宇]

jQuery 插件开发分为类级别开发和对象级别开发，但是类级别开发在真实项目中几乎不用

1.类级别的插件开发
*1.1 添加一个新的全局函数 添加...">



<meta name="robots" content="all">
<meta name="google" content="all">
<meta name="googlebot" content="all">
<meta name="verify" content="all">

    <!--Title-->


<title>JQ 中怎么样编写插件？ | 腾宇的个人博客</title>


    <link rel="alternate" href="/atom.xml" title="腾宇的个人博客" type="application/atom+xml">


    <link rel="icon" href="/favicon.ico">

    



<link rel="stylesheet" href="/blog/css/bootstrap.min.css?rev=3.3.7">
<link rel="stylesheet" href="/blog/css/font-awesome.min.css?rev=4.5.0">
<link rel="stylesheet" href="/blog/css/style.css?rev=@@hash">




    
	<div class="hide">
		<script type="text/javascript">
			var cnzz_protocol = (("https:" == document.location.protocol) ? " https://" : " http://");document.write(unescape("%3Cspan class='cnzz_stat_icon_1263868967 hide' %3E%3Cscript%20src%3D%22https%3A%2F%2Fs95.cnzz.com%2Fz_stat.php%3Fweb_id%3D1272564536%22%3E%3C%2Fscript%3E%3C/span%3E%3Cscript src='" + cnzz_protocol + "s19.cnzz.com/z_stat.php%3Fid%3D1263868967%26show%3Dpic1' type='text/javascript'%3E%3C/script%3E"));
		</script>
	</div>






    

</head>

</html>
<!--[if lte IE 8]>
<style>
    html{ font-size: 1em }
</style>
<![endif]-->
<!--[if lte IE 9]>
<div style="ie">你使用的浏览器版本过低，为了你更好的阅读体验，请更新浏览器的版本或者使用其他现代浏览器，比如Chrome、Firefox、Safari等。</div>
<![endif]-->

<body>
    <header class="main-header"  style="background-image:url(http://snippet.shenliyang.com/img/banner.jpg)"  >
    <div class="main-header-box">
        <a class="header-avatar" href="/" title='耿兵兵'>
            <img src="/blog/img/avatar.jpg" alt="logo头像" class="img-responsive center-block">
        </a>
        <div class="branding">
        	<!--<h2 class="text-hide">Snippet主题,从未如此简单有趣</h2>-->
            
                 <img src="/blog/img/branding.png" alt="Snippet 博客主题" class="img-responsive center-block">
            
    	</div>
    </div>
</header>
    <nav class="main-navigation">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="navbar-header"><span class="nav-toggle-button collapsed pull-right" data-toggle="collapse" data-target="#main-menu" id="mnav">
                    <span class="sr-only"></span>
                        <i class="fa fa-bars"></i>
                    </span>
                    <a class="navbar-brand" href="https://gitee.com/bingtengaoyu/blog">腾宇的个人博客</a>
                </div>
                <div class="collapse navbar-collapse" id="main-menu">
                    <ul class="menu">
                        
                            <li role="presentation" class="text-center">
                                <a href="/blog"><i class="fa "></i>Home</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/vuetools/#/"><i class="fa "></i>vue插件</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/reactantd/#/"><i class="fa "></i>reactAnt模板</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="https://bingtengaoyu.gitee.io/home/"><i class="fa "></i>简介</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="http://gank.io/"><i class="fa "></i>工具</a>
                            </li>
                        
                            <li role="presentation" class="text-center">
                                <a href="/blog/archives/"><i class="fa "></i>时间轴</a>
                            </li>
                        
                    </ul>
                </div>
            </div>
        </div>
    </div>
</nav>
    <section class="content-wrap">
        <div class="container">
            <div class="row">
                <main class="col-md-8 main-content m-post">
                    <p id="process"></p>
<article class="post">
    <div class="post-head">
        <h1 id="JQ 中怎么样编写插件？">
            
	            JQ 中怎么样编写插件？
            
        </h1>
        <div class="post-meta">
    
        <span class="categories-meta fa-wrap">
            <i class="fa fa-folder-open-o"></i>
            
        </span>
    

    
        <span class="fa-wrap">
            <i class="fa fa-tags"></i>
            <span class="tags-meta">
                
            </span>
        </span>
    

    
        
        <span class="fa-wrap">
            <i class="fa fa-clock-o"></i>
            <span class="date-meta">2019/07/16</span>
        </span>
        
    
</div>
            
            
    </div>
    
    <div class="post-body post-content">
        <h1 id="JQ-中怎么样编写插件？"><a href="#JQ-中怎么样编写插件？" class="headerlink" title="JQ 中怎么样编写插件？"></a>JQ 中怎么样编写插件？</h1><p>@(作者)[腾宇]</p>
<blockquote>
<p>jQuery 插件开发分为类级别开发和对象级别开发，但是类级别开发在真实项目中几乎不用</p>
</blockquote>
<h3 id="1-类级别的插件开发"><a href="#1-类级别的插件开发" class="headerlink" title="1.类级别的插件开发"></a>1.类级别的插件开发</h3><ul>
<li>*<em>1.1 添加一个新的全局函数 添加一个全局函数 *</em><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">jQuery.foo = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   alert(<span class="string">'This is a test. This is only a test.'</span>);  </span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

</li>
</ul>
<ul>
<li><p>*<em>1.2 增加多个全局函数 添加多个全局函数 *</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">jQuery.foo = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">   alert(<span class="string">'This is a test. This is only a test.'</span>);  </span><br><span class="line">&#125;;  </span><br><span class="line">jQuery.bar = <span class="function"><span class="keyword">function</span>(<span class="params">param</span>) </span>&#123;</span><br><span class="line">      alert(param);  </span><br><span class="line">&#125;;   </span><br><span class="line"><span class="comment">// 调用时和一个函数的一样的</span></span><br><span class="line">jQuery.foo();</span><br><span class="line">jQuery.bar();</span><br><span class="line"><span class="comment">// 或者</span></span><br><span class="line">$.foo();</span><br><span class="line">$.bar(<span class="string">'bar'</span>);</span><br></pre></td></tr></table></figure>
</li>
<li><p>*<em>1.3 使用jQuery.extend(object); *</em></p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">jQuery.extend(&#123;</span><br><span class="line">   foo: <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;</span><br><span class="line">      alert(<span class="string">'This is a test. This is only a test.'</span>);</span><br><span class="line">   &#125;,</span><br><span class="line">   bar: <span class="function"><span class="keyword">function</span>(<span class="params">param</span>) </span>&#123;</span><br><span class="line">      alert(<span class="string">'This function takes a parameter, which is "'</span> + param +<span class="string">'".'</span>);</span><br><span class="line">   &#125;</span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>
</li>
<li><p>*<em>1.4 使用命名空间 *</em></p>
<ul>
<li><em>然在jQuery命名空间中，我们禁止使用了大量的javaScript函数名和变量名。</em></li>
<li><em>但是仍然不可避免某些函数或变量名将于其他jQuery插件冲突，因此我们习惯将一些方法</em></li>
<li><em>封装到另一个自定义的命名空间。</em><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">jQuery.myPlugin = &#123;         </span><br><span class="line">    foo:<span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;         </span><br><span class="line">          alert(<span class="string">'This is a test.'</span>);</span><br><span class="line">    &#125;,</span><br><span class="line">    bar:<span class="function"><span class="keyword">function</span>(<span class="params">param</span>) </span>&#123;</span><br><span class="line">      alert(param);   </span><br><span class="line">    &#125;        </span><br><span class="line">&#125;; </span><br><span class="line"><span class="comment">//采用命名空间的函数仍然是全局函数，调用时采用的方法： </span></span><br><span class="line">$.myPlugin.foo();        </span><br><span class="line">$.myPlugin.bar(<span class="string">'baz'</span>);</span><br><span class="line"><span class="comment">//通过这个技巧（使用独立的插件名），我们可以避免命名空间内函数的冲突。</span></span><br></pre></td></tr></table></figure>

</li>
</ul>
</li>
</ul>
<h3 id="2-对象级别的插件开发"><a href="#2-对象级别的插件开发" class="headerlink" title="2. 对象级别的插件开发"></a>2. 对象级别的插件开发</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//形式1： </span></span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">$</span>)</span>&#123;</span><br><span class="line">    $.fn.extend(&#123;    </span><br><span class="line">       pluginName:<span class="function"><span class="keyword">function</span>(<span class="params">opt,callback</span>)</span>&#123;    </span><br><span class="line">             <span class="comment">// Our plugin implementation code goes here.      </span></span><br><span class="line">       &#125;    </span><br><span class="line">    &#125;)    </span><br><span class="line">&#125;)(jQuery);  </span><br><span class="line"></span><br><span class="line"><span class="comment">//形式2：</span></span><br><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">$</span>) </span>&#123;      </span><br><span class="line">     $.fn.pluginName = <span class="function"><span class="keyword">function</span>(<span class="params"></span>) </span>&#123;    </span><br><span class="line">        <span class="comment">// Our plugin implementation code goes here.    </span></span><br><span class="line">     &#125;;     </span><br><span class="line">&#125;)(jQuery);</span><br><span class="line"><span class="comment">//形参是$，函数定义完成之后,把jQuery这个实参传递进去.立即调用执行。</span></span><br><span class="line"><span class="comment">//这样的好处是,我们在写jQuery插件时,也可以使用$这个别名,而不会与prototype引起冲突</span></span><br></pre></td></tr></table></figure>

<p><strong>编写  jQuery 插件使库更加高效。把你最聪明、最有用的功能抽象成可重用代码，这将节省你的时间，进一步提高开发效率。下面是本文档的简要总结以及你开发下一个 jQuery 插件时的注意事项：</strong></p>
<ul>
<li>总是把插件包装在闭包中 { /* plugin goes here */ })( jQuery );</li>
<li>不在插件函数的立即作用域中额外包装 this 关键字</li>
<li>总是让插件函数返回 this 关键字以保持 chainability ，除非插件有真正的返回值。</li>
<li>不要传给插件大量参数，应该传一个可以覆盖插件默认选项的设置对象。</li>
<li>在单个插件中，不要让一个以上的名称空间搞乱了 jQuery.fn 对象。</li>
<li>总是为方法、事件和数据定义名称空间。</li>
</ul>
<h3 id="例子"><a href="#例子" class="headerlink" title="例子"></a>例子</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line">(<span class="function"><span class="keyword">function</span>(<span class="params">$</span>)</span>&#123;</span><br><span class="line">    $.fn.starRating = <span class="function"><span class="keyword">function</span>(<span class="params">options</span>)</span>&#123;</span><br><span class="line">        <span class="keyword">var</span> defaults = &#123;</span><br><span class="line">            num:<span class="number">2</span></span><br><span class="line">        &#125;</span><br><span class="line">        <span class="keyword">var</span> settings = $.extend(&#123;&#125;,defaults,options);</span><br><span class="line">        <span class="keyword">var</span> starLight = <span class="function"><span class="keyword">function</span>(<span class="params">items,num</span>)</span>&#123;</span><br><span class="line">            items.each(<span class="function"><span class="keyword">function</span>(<span class="params">i,elem</span>)</span>&#123;</span><br><span class="line">                <span class="keyword">if</span>(i&lt;=num)&#123;</span><br><span class="line">                    $(<span class="keyword">this</span>).addClass(<span class="string">"on"</span>);</span><br><span class="line">                &#125;<span class="keyword">else</span>&#123;</span><br><span class="line">                    $(<span class="keyword">this</span>).removeClass(<span class="string">"on"</span>)</span><br><span class="line">                &#125;</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;;  </span><br><span class="line">        <span class="comment">// 这种函数声明是赋值写法，最后需要加分号 **;**</span></span><br><span class="line">        <span class="keyword">var</span> init = <span class="function"><span class="keyword">function</span>(<span class="params">el,num</span>)</span>&#123;</span><br><span class="line">            <span class="keyword">var</span> starList = $(el),</span><br><span class="line">            items = starList.find(<span class="string">".star-item"</span>);</span><br><span class="line">            starLight(items,num<span class="number">-1</span>);</span><br><span class="line">            starList.on(<span class="string">"mouseover"</span>,<span class="string">".star-item"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                starLight(items,$(<span class="keyword">this</span>).index())</span><br><span class="line">            &#125;).on(<span class="string">"click"</span>,<span class="string">".star-item"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                num = $(<span class="keyword">this</span>).index();</span><br><span class="line">            &#125;).on(<span class="string">"mouseout"</span>,<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">                starLight(items,num)</span><br><span class="line">            &#125;)</span><br><span class="line">        &#125;;</span><br><span class="line">        <span class="keyword">return</span> <span class="keyword">this</span>.each(<span class="function"><span class="keyword">function</span>(<span class="params"></span>)</span>&#123;</span><br><span class="line">            num = settings.num;</span><br><span class="line">            init(<span class="keyword">this</span>,num);</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">&#125;)(jQuery)</span><br><span class="line"></span><br><span class="line">$(<span class="string">".star-list"</span>).starRating(&#123;</span><br><span class="line">    num:<span class="number">3</span></span><br><span class="line">&#125;);</span><br></pre></td></tr></table></figure>


    </div>
    
    <div class="post-footer">
        <div>
            
                转载声明：商业转载请联系作者获得授权,非商业转载请注明出处 © <a href="" target="_blank">Snippet</a>
            
        </div>
        <div>
            
        </div>
    </div>
</article>

<div class="article-nav prev-next-wrap clearfix">
    
        <a href="/blog/2019/07/17/Vue 组件 data 为什么是函数/" class="pre-post btn btn-default" title='Vue 组件 data 为什么是函数?'>
            <i class="fa fa-angle-left fa-fw"></i><span class="hidden-lg">上一篇</span>
            <span class="hidden-xs">Vue 组件 data 为什么是函数?</span>
        </a>
    
    
        <a href="/blog/2019/07/16/document.write 和 innerHTML 的区别/" class="next-post btn btn-default" title='document.write 和 innerHTML 的区别'>
            <span class="hidden-lg">下一篇</span>
            <span class="hidden-xs">document.write 和 innerHTML 的区别</span><i class="fa fa-angle-right fa-fw"></i>
        </a>
    
</div>


    <div id="comments">
        
	
    <div id="vcomments" class="valine"></div>
    <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
<script src="/blog/assets/valine.min.js"></script>

    <script>
        new Valine({
            av: AV,
            el: '#vcomments',
            appId: 'xOKV9J4UeQAtVkvnJC7Kq2Jn-gzGzoHsz',
            appKey: 'erIpQac4azoCmgfBB7Dl9maa',
            placeholder: '说点什么吧',
            notify: false,
            verify: true,
            avatar: 'mm',
            meta: 'nick,mail'.split(','),
            pageSize: '10',
            path: window.location.pathname,
            lang: ''.toLowerCase()
        })
    </script>


    </div>





                </main>
                
                    <aside id="article-toc" role="navigation" class="col-md-4">
    <div class="widget">
        <h3 class="title">Table of Contents</h3>
        
            <ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#JQ-中怎么样编写插件？"><span class="toc-text">JQ 中怎么样编写插件？</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#1-类级别的插件开发"><span class="toc-text">1.类级别的插件开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#2-对象级别的插件开发"><span class="toc-text">2. 对象级别的插件开发</span></a></li><li class="toc-item toc-level-3"><a class="toc-link" href="#例子"><span class="toc-text">例子</span></a></li></ol></li></ol></li></ol>
        
    </div>
</aside>

                
            </div>
        </div>
    </section>
    <footer class="main-footer">
    <div class="container">
        <div class="row">
        </div>
    </div>
</footer>

<a id="back-to-top" class="icon-btn hide">
	<i class="fa fa-chevron-up"></i>
</a>




    <div class="copyright">
    <div class="container">
        <div class="row">
            <div class="col-sm-12">
                <div class="busuanzi">
    
</div>

            </div>
            <div class="col-sm-12">
                <span>Copyright &copy; 2017
                </span> |
                <span>
                    Powered by <a href="//hexo.io" class="copyright-links" target="_blank" rel="nofollow">Hexo</a>
                </span> |
                <span>
                    Theme by <a href="//github.com/shenliyang/hexo-theme-snippet.git" class="copyright-links" target="_blank" rel="nofollow">Snippet</a>
                </span>
            </div>
        </div>
    </div>
</div>







<script src="/blog/js/app.js?rev=@@hash"></script>

</body>
</html>